/**
 * 
 */
package com.wolfpire.info.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.info.dao.TeaSciResearchInfoDao;
import com.wolfpire.info.model.TeaSciResearchInfo;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;

/**
 * @author lihd
 *
 */

@Repository("teaSciResearchInfoDao")
public class TeaSciResearchInfoDaoImpl extends
		BaseHibernateDao<TeaSciResearchInfo, Long> implements
		TeaSciResearchInfoDao {

	@Override
	public Page<TeaSciResearchInfo> findTeaSciResearchInfos(
			Page<TeaSciResearchInfo> page,
			TeaSciResearchInfo filterTeaSciResearchInfo) {
		Criterion[] criterions = this.createFilter(filterTeaSciResearchInfo);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		
		if (0 < totalCount) {
			Criteria c = this.createCriteria(criterions);
			c.addOrder(Order.desc("endYear"));
			c.addOrder(Order.asc("startYear"));
			c.addOrder(Order.desc("id"));
			c = this.setPageParameter(c, page);
			@SuppressWarnings("unchecked")
			List<TeaSciResearchInfo> result = c.list();
			page.setDataList(result);
		}
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TeaSciResearchInfo> list(TeaSciResearchInfo teaSciResearchInfo) {
		Criterion[] criterions = this.createFilter(teaSciResearchInfo);
		Criteria c = this.createCriteria(criterions);
		return c.list();
	}
	
	private Criterion[] createFilter(TeaSciResearchInfo filterTeaSciResearchInfo) {
		if (null == filterTeaSciResearchInfo) {
			return null;
		}
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (null != filterTeaSciResearchInfo.getId()) {
			criterions.add(Restrictions.eq("id", filterTeaSciResearchInfo.getId()));
		}
		if (null != filterTeaSciResearchInfo.getStartYear()) {
			criterions.add(Restrictions.ge("startYear", filterTeaSciResearchInfo.getStartYear()));
		}
		if (null != filterTeaSciResearchInfo.getEndYear()) {
			criterions.add(Restrictions.le("endYear", filterTeaSciResearchInfo.getEndYear()));
		}
		if (null != filterTeaSciResearchInfo.getDelFlag()) {
			criterions.add(Restrictions.eq("delFlag", filterTeaSciResearchInfo.getDelFlag()));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}
}
